/*
		A Random image module for the desktop2 system, as a bacground image, centered but not stretched
		
		Author: 	Matthew Allpress
		Created:	21/06/06
		Edited:		24/09/06

*/


var image_mod_name = "Random Images";


var ImageBackend = "http://localhost:5050/todo/index.php?mid=1";

var image_url = Array();

var toAdd = "<table border=\"0\" width=\"100%\" height=\"100%\" align=\"center\">\n";
toAdd+= "\t<tr>\n";
toAdd+= "\t\t<td valign=\"middle\"><center><img src=\"images/loading.jpg\" id=\"randomImage\"></center></td>\n";
toAdd+= "\t	</tr>\n";
toAdd+= "</table>\n";

document.body.innerHTML+=toAdd;

toAdd = null;

window.setInterval("change_image()", 25000);

document.bgColor = module_config[image_mod_name]['background'];
//module_config[image_mod_name] = null;

function callUpdateImages()
{
	makeNewRequest("GET", ImageBackend, ImageReqChange);
}

callUpdateImages();

function ImageReqChange() 
{
 // If data received correctly
 if (XMLRequestObject.readyState == 4) 
 {
  //alert(XMLRequestObject.responseText);
  // if data is valid
  if (XMLRequestObject.responseText.indexOf('invalid') == -1) 
  { 	
   // Parsing RSS
   try
   {
	   var node = XMLRequestObject.responseXML.documentElement; 
	   // Get Channel information
	   var images = node.getElementsByTagName('url');
	   image_url = Array();
	   
	   for (var i=0; i < images.length; i++)
	   {
			var url = images.item(i).childNodes[0].nodeValue;
			image_url[i] = url;
	   }
	   node = null;
	   images = null;
	   i = null;
	   change_image();
	}
	catch(err)
	{
		add_to_console("Error returned when calling images update, retrying");
		callUpdateImages();
	}
  }
  else 
  {
   // Tell the reader that there was error requesting data
   alert("ERROR (Images Feed): There was an error requesting the data");
  }
 }
}



function change_image() {
 var picnum = Math.round(Math.random() * image_url.length - 1);
 if(image_url.length > 0)
 {	
	if(image_url[picnum] == null)
	{
		randomImage.src = "images/loading.jpg";
		change_image();
	}
	else
	{
		randomImage.src = image_url[picnum];
	}
 }
 else
 {
	makeNewRequest("GET", ImageBackend, ImageReqChange);
 }
 picnum = null;
}


